<template>
  <vxe-pulldown ref="xDown">
    <template #default>
      <el-input
        v-model="searchValue"
        clearable
        @focus="focusEvent"
        @input="search"
      />
    </template>
    <template #dropdown>
      <div class="my-dropdown" :style="{ height: `${$props.height}px` }">
        <BasicTree
          :data="treeData"
          :search-value="searchValue"
          @register="register"
          @treeClick="treeClick"
        />
      </div>
    </template>
  </vxe-pulldown>
</template>

<script>
import { defineComponent, ref, computed, watchEffect, unref } from 'vue'
import { useTree } from '../../../tree'
import { isFunction, isArray, get } from 'lodash-es'

export default defineComponent({
  name: 'ApiTreeSelect',
  props: {
    // 下拉框高度
    height: {
      type: Number,
      default: 220
    },
    api: {
      type: Function,
      required: true
    },
    params: {
      type: Object,
      default: () => {}
    },
    resultField: {
      type: String,
      default: ''
    },
    // 是否立即请求
    immediate: {
      type: Boolean,
      default: true
    },
    // 自定义节点 label、children 的字段
    fieldNames: {
      type: Object,
      default: () => ({ label: 'unitName', children: 'children' })
    }
  },
  emits: ['options-change'],
  setup(props, { emit, attrs }) {
    const xDown = ref(null)
    const treeRef = ref(null)
    const searchValue = ref('')
    const treeData = ref([])
    const copyTreeData = ref('')

    const getReplaceFields = computed(() => {
      return {
        label: 'unitName',
        children: 'children',
        ...props.fieldNames
      }
    })

    const [register, { filter }] = useTree({
      search: false,
      showHeader: false,
      defaultExpandAll: true,
      height: props.height,
      fieldNames: unref(getReplaceFields),
      ...attrs
    })

    watchEffect(() => {
      props.immediate && fetch()
    })

    function focusEvent() {
      xDown.value.showPanel()
    }

    function search(e) {
      searchValue.value = e
      const copyData = JSON.parse(unref(copyTreeData))
      if (!e) {
        treeData.value = copyData
      } else {
        copyData.filter(item => item)
      }
      filter(e.trim())
      emit('options-change', e)
    }

    function treeClick(e) {
      searchValue.value = e[unref(getReplaceFields).label]
      xDown.value.hidePanel()
    }

    async function fetch() {
      const { api, params } = props
      if (!api && !isFunction(api)) return
      treeData.value = []
      const res = await api(params)
      if (isArray(res)) {
        treeData.value = res
      } else {
        props.resultField &&
          (treeData.value = get(res, props.resultField) || [])
      }
      copyTreeData.value = JSON.stringify(unref(treeData))
    }

    return {
      xDown,
      treeRef,
      searchValue,
      treeData,

      focusEvent,
      search,
      register,
      treeClick
    }
  }
})
</script>

<style lang="scss">
::v-deep {
  .vxe-pulldown {
    width: 100%;
  }
}
.my-dropdown {
  height: 200px;
  // overflow: auto;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
}
</style>
